/**
 * Filename : VSSendHeartBeat.java
 * Author : morris
 * Creation time : 2013-4-18 上午10:33:53
 * Description : 
 */
package cn.com.sbell.vss.csg.heartbeat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.RuntimeIOException;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.SocketConnector;
import org.apache.mina.transport.socket.nio.SocketConnectorConfig;

public class VSHeartBeatSender {
	private static final String HOSTADDR = "192.169.6.75";
	private static final int PORT = 10002;
	private static final int CONNECT_TIMEOUT = 30;

	public static void main(String[] args) throws UnknownHostException,
			IOException, InterruptedException {
		SocketConnector connector = new SocketConnector();
		connector.setWorkerTimeout(1);
		SocketConnectorConfig cfg = new SocketConnectorConfig();
		cfg.setConnectTimeout(CONNECT_TIMEOUT);

		cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new VSHeartBeatProtocolCodecFactory()));
		cfg.getFilterChain().addLast("logger", new LoggingFilter());

		HeartBeatMessage msg = new HeartBeatMessage();
		//msg.setMessageType(HeartBeatMessage.REGISTER);
		msg.setMessageType(HeartBeatMessage.HEARTBEAT);
		msg.setPort(80);
		msg.setServerIp("192.168.6.149");
		msg.setAccessPassword("admin");
		msg.setServerName("admin");
		msg.setServerType("VS");
		msg.setPeriod(3000);
		msg.setNeedAcknowledge(true);
		
		//ConnectFuture future = connector.connect(new InetSocketAddress(HOSTADDR, PORT), new VSHeartBeatHandler(msg), cfg);
		
		IoSession session;
		for (;;) {
			try {
				ConnectFuture future = connector.connect(new InetSocketAddress(HOSTADDR, PORT), new VSHeartBeatHandler(msg), cfg);
				future.join();
				session = future.getSession();
				break;
			} catch (RuntimeIOException e) {
				System.err.println("Failed to connect.");
				e.printStackTrace();
				Thread.sleep(5000);
			}
		}

		// wait until the summation is done
		//session.getCloseFuture().join();

		// Socket socket = new Socket();
		// socket.connect(new InetSocketAddress(HOSTADDR, PORT));

	}

}
